<template>
  <view :style="[styles, { '--themeColor': themeColor }]" id="nearby-stores">
    <view class="nearby-stores-list">
      <block v-if="isFixed">
        <view :style="{ height: nearByTagsHeight + 'px' }"></view>
        <view
          class="nearby-stores-tags"
          id="nearby-stores-tags"
          :class="{ 'nearby-stores-tags-fixed': isFixed }"
          :style="{ top: navBarHeight + 'rpx' }"
        >
          <view class="tags-title fixed-tags-title">
            <image
              class="nearby-stores-icon"
              src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/116/20230413/b496840a-a85d-4938-aaf6-8bdbdc1ff824.png"
            />
            <text class="tags-title-name">附近门店</text>
          </view>
          <view class="tags">
            <view
              class="tag fixed-tag"
              v-for="item in tagOptions"
              :key="item.sortType"
              @click="handleChangeTags(item)"
              :style="{
                backgroundColor:
                  params.sortType === item.sortType ? themeColor : '#ffffff',
                color: params.sortType === item.sortType ? 'white' : '#999999',
              }"
              >{{ item.label }}</view
            >
          </view>
        </view>
      </block>
      <view
        v-else
        class="nearby-stores-tags"
        id="nearby-stores-tags"
        :class="{ 'nearby-stores-tags-fixed': isFixed }"
        :style="{ top: navBarHeight + 'rpx' }"
      >
        <view class="tags-title">
          <image
            class="nearby-stores-icon"
            src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/116/20230413/b496840a-a85d-4938-aaf6-8bdbdc1ff824.png"
          />
          <text class="tags-title-name">附近门店</text></view
        >
        <view class="tags">
          <view
            class="tag"
            v-for="item in tagOptions"
            :key="item.sortType"
            @click="handleChangeTags(item)"
            :style="{
              backgroundColor:
                params.sortType === item.sortType ? themeColor : '#ffffff',
              color: params.sortType === item.sortType ? 'white' : '#999999',
            }"
            >{{ item.label }}</view
          >
        </view>
      </view>
      <block v-if="list.length > 0">
        <view v-for="(item, index) in list" :key="item.id" class="list-item">
          <view class="item-cover" @click="handleToShop(item)">
            <image :src="baseUrl + item.logo" class="item-cover-img" />
            <view
              class="hot"
              v-if="item.pubTag && Number(item.shopType) === 3"
              :style="{
                backgroundColor: themeColor ? themeColor : '#ffb72f',
              }"
            >
              <image
                src="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/img/pub/hot-business-district.png"
                class="hot-img"
              />
              热门商圈
            </view>
          </view>
          <view class="item-container">
            <view class="item-shop-name-container">
              <div
                class="title-Hidden-one item-shop-name"
                @click="handleToShop(item)"
              >
                {{ item.name }}
              </div>
              <div
                class="item-distance"
                v-if="item.distance"
                @click="handleToShop(item)"
              >
                {{ item._distance }}
              </div>
            </view>
            <view class="item-shop-info" @click="handleToShop(item)">
              <text>
                <text v-if="!!item.pubTag && Number(item.shopType) === 3">
                  商家{{ item.shopNumbers || 0 }}
                </text>
                <text v-else> {{ item.type }}</text>
              </text>
              <text style="padding: 0 10rpx">|</text>
              <text>月售{{ item.monthSales }}</text>
            </view>
            <view
              v-if="item.balanceActivityDesc && !item.pubTag"
              class="item-active balanceActivityDesc"
              :style="{
                color: themeColor,
                border: `1rpx solid ${themeColor}`,
              }"
              >{{ item.balanceActivityDesc }}</view
            >
            <view class="bottom">
              <view
                class="ticket"
                v-if="!!item.pubTag && Number(item.shopType) === 3"
              >
                <scroll-view class="ticket_list" scroll-x="true">
                  <view
                    class="ticket_item"
                    v-for="(coupon, couponsIndex) in item.pubCoupons"
                    :key="coupon.id"
                    @click="pullDownCoupon(coupon, index, couponsIndex)"
                  >
                    <view class="discount">
                      <view v-if="coupon.denomination > 0" class="discount-unit"
                        >¥</view
                      >
                      <view class="discount-content">{{
                        coupon.denomination > 0
                          ? coupon.denomination / 100
                          : coupon.discountPercent / 10
                      }}</view>
                      <view
                        v-if="!coupon.denomination > 0"
                        class="discount-unit"
                        >折</view
                      >
                    </view>
                    <view class="rule">
                      满{{ coupon.transactionMinimum / 100 }}元可用
                    </view>
                    <view :class="['get', coupon.pullDown ? 'took' : '']">
                      {{ coupon.pullDown ? "已领" : "领" }}
                    </view>
                  </view>
                </scroll-view>
                <view
                  class="see_all"
                  v-if="item.pubCoupons && item.pubCoupons.length >= 2"
                  @click="handleToShop(item, true)"
                >
                  查看更多
                </view>
              </view>
            </view>
          </view>
        </view>
      </block>
      <view v-else style="margin: 10rpx 0; padding-bottom: 40rpx">
        <u-empty
          mode="list"
          icon="https://cdn.uviewui.com/uview/empty/list.png"
        />
      </view>
    </view>
  </view>
</template>

<script>
import { COMPREIFX } from "../../../libs/const/widget";
const SHOP_TYPE = {
  1: "餐饮",
  2: "便利店",
  3: "休闲娱乐",
  4: "美容美发",
};
export default {
  name: `${COMPREIFX}nearby-stores-list`,
  props: {
    attribute: Object,
    styles: Object,
    // navBarHeight: {
    //   type: Number,
    //   default: 88, //单位rpx
    // },
  },
  data() {
    return {
      sign: `${COMPREIFX}nearby-stores-list`,
      list: [],
      params: {
        pageSize: 20,
        pageNum: 1,
        // 纬度
        latitude: "",
        // 精度
        longitude: "",
        // 门店名称
        shopName: "",
        // 门店类型 1餐饮；2便利店；3休闲娱乐；4美容美发， 0查全部类型
        shopType: "",
        // 排序规则 1综合排序 2距离优先 3人气优先
        sortType: 1,
      },
      nearByTopDistance: 0,
      navBarHeight: 88, //单位rpx
      isFixed: false,
      tagOptions: [
        {
          label: "综合排序",
          sortType: 1,
        },
        {
          label: "距离优先",
          sortType: 2,
        },
        {
          label: "人气优先",
          sortType: 3,
        },
      ],
      baseUrl: "https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/",
      hasNextPage: false,
      nearByTagsHeight: 0,
      systemInfo: {},
      windowWidth: 750,
      onePxToRpx: 2,
    };
  },
  computed: {
    getUserLocation() {
      return this.$getCurrentLocation();
    },
    themeColor({ $theme }) {
      return $theme?.themeColor?.primary;
    },
  },
  watch: {
    getUserLocation: {
      handler() {
        this.$nextTick(() => {
          this.innit(true);
        });
      },
      deep: true,
    },
  },
  created() {
    this.innitTop();
    this.innitToken();
  },
  mounted() {
    const systemInfo = uni.getSystemInfoSync();
    const windowWidth = systemInfo.windowWidth;
    const onePxToRpx = 750 / windowWidth;
    this.systemInfo = systemInfo;
    this.windowWidth = windowWidth;
    this.onePxToRpx = onePxToRpx;
  },
  methods: {
    innitToken() {
      const token = uni.getStorageSync("PUB_MINI_APP_CATCH_TOKEN");
      if (!token) {
        return setTimeout(() => {
          this.innitToken();
        }, 300);
      }
      this.$nextTick(() => {
        this.innit(true);
      });
    },
    async innit(isClear = false) {
      const userLocation = this.$getCurrentLocation();
      this.params.latitude = userLocation?.latitude || "";
      this.params.longitude = userLocation?.longitude || "";
      const getNearList = this.$widget[this.attribute.api.getNearList];
      const getIndustry = this.$widget[this.attribute.api.getIndustry];
      const data = await getIndustry();
      const { hasNextPage, list } = await getNearList(this.params);
      if (list?.length > 0) {
        list.map((v) => {
          v.type = data[Number(v.shopType)];
          if (v.distance) {
            if (v.distance > 1000) {
              const distance = (v.distance / 1000).toFixed(2) + "km";
              v._distance = distance;
            } else {
              v._distance = v.distance.toFixed(2) + "m";
            }
          }
          if (v.pubCoupons) {
            v.pubCoupons.map((pubCoupon) => {
              pubCoupon.pullDown = false;
            });
          }
        });
      }
      this.list = isClear ? list || [] : [...this.list, ...list];
      this.hasNextPage = hasNextPage;
      // console.log("附近门店", this.params);
    },

    // 领取优惠券
    pullDownCoupon(coupon, parentIndex, couponsIndex) {
      const receiveCoupon = this.$widget[this.attribute.api.receiveCoupon];
      let { receiveCode } = coupon;
      let { list } = this;
      if (!list[parentIndex]?.pubCoupons) return;
      if (list[parentIndex].pubCoupons[couponsIndex].pullDown) return;
      receiveCoupon({
        receiveCode,
      })
        .then(() => {
          this.list[parentIndex].pubCoupons[couponsIndex].pullDown = true;
          this.handleToShop(list[parentIndex])
          uni.showToast({
            icon: "none",
            title: "领取成功，赶快去下单吧~",
          });
        })
        .catch((err) => {
          uni.showToast({
            title: err?.msg,
            icon: "none",
          });
        });
    },
    innitTop() {
      let query = uni.createSelectorQuery().in(this);
      query
        .select("#nearby-stores-tags")
        .boundingClientRect((data) => {
          // console.log("距离顶部", data);
          this.nearByTagsHeight = data?.height;
          this.nearByTopDistance = data?.top;
        })
        .exec();
    },
    handleChangeTags(row) {
      if (this.params.sortType === row.sortType) return;
      this.params.sortType = row.sortType;
      this.params.pageSize = 20;
      this.params.pageNum = 1;
      this.$nextTick(() => {
        this.innit(true);
      });
    },
    handleFixNearByTags(height, scrollTop) {
      const systemInfo = uni.getSystemInfoSync();
      this.navBarHeight = height;
      this.isFixed =
        scrollTop > 45 &&
        scrollTop >
          this.nearByTopDistance -
            height +
            systemInfo.statusBarHeight * this.onePxToRpx;
      // console.log("执行", scrollTop, this.nearByTopDistance, height);
    },
    handleNextPage() {
      if (!this.hasNextPage) return;
      this.params.pageNum = this.params.pageNum + 1;
      this.$nextTick(() => {
        this.innit(false);
      });
    },
    handleToShop(item, showTicket = false) {
      if (item.pubTag && Number(item.shopType) === 3) {
        uni.navigateTo({
          url: `pages/sp-store/pages/business-district-index-page/index?shopId=${item.id}&showTicket=${showTicket}`,
        });
      } else {
        uni.navigateTo({
          url: `pages/sp-store/pages/shop-index/index?shopId=${item.id}`,
        });
      }
    },
    handleSearch(val) {
      this.params.pageSize = 20;
      this.params.pageNum = 1;
      this.params.shopName = val;
      this.$nextTick(() => {
        this.innit(true);
      });
    },
  },
};
</script>

<style scoped lang="scss">
.title-Hidden-one {
  overflow: hidden;
  word-break: keep-all;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: block;
}
.nearby-stores-list {
  width: 95%;
  // background: #ffffff;
  border-radius: 10rpx;
  margin: 0 auto;
  font-family: PingFang SC;
  .nearby-stores-tags {
    padding: 28rpx 0;
    display: flex;
    align-items: center;
    .fixed-tag:last-child {
      margin-right: 20rpx;
    }
    .tags {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .tag {
        padding: 11rpx 16rpx;
        background: #ffffff;
        border-radius: 28rpx;
        font-size: 24rpx;
        margin-left: 26rpx;
      }
      .tag-active {
        background-color: #ffb72f;
        color: white;
      }
    }
    .fixed-tags-title {
      margin-left: 22rpx;
    }
    .tags-title {
      font-size: 28.98rpx;
      font-weight: bold;
      color: #1a1a1a;
      // padding-left: 22rpx;
      display: flex;
      align-items: center;
      .tags-title-name {
        font-size: 29rpx;
        margin-left: 15rpx;
      }
      .nearby-stores-icon {
        width: 35rpx;
        height: 35rpx;
      }
    }
    &-fixed {
      position: fixed;
      width: 100vw;
      top: 0;
      z-index: 999;
      background-color: white;
      left: 0;
    }
  }
  .list-item {
    display: flex;
    padding: 23rpx 23rpx 26rpx 23rpx;
    background: #ffffff;
    border-radius: 18rpx;
    margin-bottom: 13rpx;
    .item-cover {
      width: 190rpx;
      height: 190rpx;
      position: relative;
      &-img {
        width: 190rpx;
        height: 190rpx;
        border-radius: 10rpx;
      }
      .hot {
        position: absolute;
        left: 0;
        top: 0;
        color: #ffeee5;
        display: flex;
        align-items: center;
        border-radius: 15rpx 0rpx 15rpx 0rpx;
        padding: 8rpx 14rpx 8rpx 10rpx;
        font-size: 20rpx;
        .hot-img {
          width: 20rpx;
          height: 20rpx;
          margin-right: 5rpx;
        }
      }
    }
    .item-container {
      padding-left: 22rpx;
      flex: 1;
      position: relative;

      .bottom {
        width: 100%;
        position: absolute;
        bottom: 0;
      }
      .item-active {
        background: #fff5f0;
        border: 1px solid #ffb72f;
        border-radius: 6rpx;
        color: #ffb72f;
        display: inline-block;
        font-size: 22rpx;
        padding: 3rpx 7rpx;
        margin-top: 18rpx;
      }
      .item-shop-name-container {
        font-size: 30rpx;
        font-weight: bold;
        color: #1a1a1a;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        // width: 400rpx;
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        .item-shop-name {
          font-size: 32rpx;
          width: 329rpx;
        }
        .item-distance {
          font-size: 24rpx;
          color: #999999;
          font-weight: normal;
        }
      }
      .item-shop-info {
        font-size: 24rpx;
        font-weight: 500;
        color: #999999;
        position: relative;
        margin-top: 16rpx;
      }
    }
    .ticket {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      //margin: 0 auto;
      margin-top: 24rpx;
      font-family: PingFang SC;
      .ticket_list {
        flex: 1;
        overflow: hidden;
        white-space: nowrap;
        width: 100rpx;
        .ticket_item {
          font-size: 16rpx;
          font-family: PingFang SC;
          font-weight: 500;
          background-color: #fff5f0;
          position: relative;
          z-index: 5;
          align-items: center;
          height: 34rpx;
          color: #daa629;
          border: 1rpx solid #daa629;
          padding: 0 9rpx 0 4rpx;
          overflow: hidden;
          margin-right: 20rpx;
          border-radius: 6rpx;
          display: inline-flex;

          .discount {
            font-size: 20rpx;
            font-family: PingFang SC;
            color: #daa629;
            border-right: 1px dashed #daa629;
            padding-right: 9rpx;
            display: inline-flex;
            align-items: baseline;
            .discount-unit {
              font-size: 16rpx;
              color: var(--theme-color);
              padding: 1rpx;
            }
            .discount-content {
              font-size: 20rpx;
              font-weight: 500;
              color: var(--theme-color);
            }
          }

          .rule {
            display: inline-block;
            position: relative;
            margin-right: 15rpx;
            font-size: 16rpx;
            padding-left: 8rpx;
          }

          .get {
            width: 24rpx;
            height: 24rpx;
            background: var(--theme-color);
            font-size: 16rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #ffffff;
            border-radius: 6rpx;
            align-items: center;
            display: flex;
            justify-content: center;
            &.took {
              background: transparent;
              border-left: 1rpx solid var(--theme-color);
              color: var(--theme-color);
              border-radius: 0;
              padding-left: 10rpx;
            }
          }
        }
      }

      .see_all {
        white-space: nowrap;
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: var(--theme-color);
        margin-left: 10rpx;
      }
    }
  }
}
</style>
